package com.binguo.api.controller;


import com.alibaba.fastjson.JSONObject;
import com.binguo.api.form.CardInfoForm;
import com.binguo.api.form.CustomerForm;
import com.binguo.api.form.FaceForm;

import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.JsonUtil;
import com.binguo.helper.ImgHelper;
import com.binguo.model.api.vo.CustomerVO;
import com.binguo.model.model.*;
import com.binguo.model.repository.LogFaceRecRepository;
import com.binguo.model.repository.ShiminkaFacePayRepository;
import com.binguo.service.CustomerService;
import com.binguo.service.ShopService;
import com.binguo.thirdPay.dashiPay.DaShiPay;
import com.binguo.thirdPay.hzShiMing.HZShiMingFaceService;
import com.binguo.thirdPay.hzShiMing.HZShiMingService;
import com.binguo.thirdPay.jinQiao.JinQiaoPayCardItem;
import com.binguo.thirdPay.jinQiao.JinQiaoPayController;
import com.binguo.thirdPay.zy.ZytkService;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;

import static com.binguo.common.exception.ErrorCode.CUSTOMER_NOT_EXIST;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;


/**
 * Created by haibang on 18/5/7.
 */
@Api(tags = "收银端: 顾客")
@RestController
@RequestMapping
public class CustomerController {

    private static Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    CustomerService customerService;

    @Autowired
    ZytkService zytkService;

    @Autowired
    HZShiMingService hzShiMingService;

    @Autowired
    HZShiMingFaceService hzShiMingFaceService;

    @Autowired
    ShopService shopService;

    @Autowired
    DaShiPay daShiPay;

    @Autowired
    ShiminkaFacePayRepository shiminkaFacePayRepository;

    @Autowired
    LogFaceRecRepository logFaceRecRepository;

    private String ipAddress;

    public CustomerController(){
        this.ipAddress = System.getenv().get("ipAddress");
    }



    @PostMapping(value = "/api/customer")
    @ApiOperation(value = "获取单个顾客信息", notes = "通过顾客id")
    public Result getCustomer(@RequestBody FaceForm form) {
        Shop shop = shopService.findShopById(form.getShopId());
        if (shop.getPayType() == 9) {
            form.setFaceUrl(form.getFaceUrl().replaceAll("\r|\n", ""));
            Long s = System.currentTimeMillis();
            logger.info("F1Start" + s);
            ThreadManager.executorService.submit(new Runnable() {
                @Override
                public void run() {
                    String uuid = UUID.randomUUID().toString();
                    StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/faces/")
                            .append(form.getShopId());

                    /*StringBuffer outputFilepathStringBuffer = new StringBuffer("C:/Program Files (x86)/apache-tomcat-8.5.47/webapps/ROOT/")
                        .append(form.getShopId());*/

                    File dirOutput = new File(outputFilepathStringBuffer.toString());
                    if (!dirOutput.exists()) {
                        dirOutput.mkdir();
                    }
                    String newFileName = outputFilepathStringBuffer.append("/").append(uuid).append(".png").toString();

                    String httpFileName = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/images/faces/")
                            .append(form.getShopId()).append("/").append(uuid).append(".png").toString();

                    /*String httpFileName = new StringBuffer("http://")
                        .append("123.206.224.209")
                        .append(":8080/")
                        .append(form.getShopId()).append("/").append(uuid).append(".png").toString();*/

                    ImageBase64Util.base64StringToImage(form.getFaceUrl(), newFileName);


                    ShiminkaFacePay shiminkaFacePay = new ShiminkaFacePay();
                    shiminkaFacePay.setCreatedtime(new Date());
                    shiminkaFacePay.setFaceurl(httpFileName);
                    shiminkaFacePay.setShopid(form.getShopId());
                    shiminkaFacePayRepository.save(shiminkaFacePay);
                }
            });
            CustomerVO customerVO = customerService.findByShiMingFace(form.getFaceUrl());
            if (null == customerVO) {
                throw new ServiceException(CUSTOMER_NOT_EXIST);
            }
            logger.info("" + (System.currentTimeMillis() - s));
            logger.info("F1End" + System.currentTimeMillis());
            return ResultGenerator.genSuccessResult(customerVO);
        }
        if (shop.getPayType() == 14) {
            String imgBase64 = ImgHelper.imgBase64(form.getFaceUrl());
            imgBase64 = imgBase64.replaceAll("\r|\n", "");
            String uuid = UUID.randomUUID().toString();
            logger.info(daShiPay.dsFaceSwiging(uuid, imgBase64, "0.01"));
            throw new ServiceException(CUSTOMER_NOT_EXIST);
        } else {
            if (!form.getFaceUrl().startsWith("http")) {
                String uuid = UUID.randomUUID().toString();
                StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/faces/")
                        .append(form.getShopId());

                File dirOutput = new File(outputFilepathStringBuffer.toString());
                if (!dirOutput.exists()) {
                    dirOutput.mkdir();
                }
                String newFileName = outputFilepathStringBuffer.append("/").append(uuid).append(".png").toString();

                String httpFileName = new StringBuffer("http://")
                        .append(ipAddress)
                        .append(":8019/images/faces/")
                        .append(form.getShopId()).append("/").append(uuid).append(".png").toString();


                //System.out.println(httpFileName);

                ImageBase64Util.base64StringToImage(form.getFaceUrl(), newFileName);

                form.setFaceUrl(httpFileName);
            }
            try {
                logger.info("api/customer: {}", JsonUtil.toJson(form));
                logger.info(JsonUtil.toJson(form));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            Long s = System.currentTimeMillis();
            logger.info("F1Start" + s);
            CustomerVO vo = customerService.findByFaceNew(form.getShopId(), form.getFaceUrl());
            logger.info("" + (System.currentTimeMillis() - s));
            logger.info("F1End" + System.currentTimeMillis());
            try {
                logger.info(JsonUtil.toJson(vo));
                ThreadManager.executorService.submit(() -> {
                    LogFaceRec logFaceRec = new LogFaceRec();
                    logFaceRec.setCustomerId(vo.getCustomerId());
                    logFaceRec.setFaceUrl(form.getFaceUrl());
                    logFaceRec.setShopId(form.getShopId());
                    logFaceRec.setCreateTime(new Date());
                    logFaceRecRepository.save(logFaceRec);
                });
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return ResultGenerator.genSuccessResult(vo);
        }
    }

    @PostMapping(value = "/api/customerByFile")
    @ApiOperation(value = "获取单个顾客信息", notes = "通过顾客id")
    public Result getCustomerByFile(@RequestParam(value = "file", required = false) MultipartFile file,
                                    @RequestParam(value = "shopId", required = false) Integer shopId) {

        if (file == null || shopId == null) {
            return ResultGenerator.genFailResult("参数错误");
        }

        FaceForm form = new FaceForm();
        if (shopId != null) {
            form.setShopId(shopId);
        }

        try {
            String uuid = UUID.randomUUID().toString();
            StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/faces/")
                    .append(form.getShopId());

            File dirOutput = new File(outputFilepathStringBuffer.toString());
            if (!dirOutput.exists()) {
                dirOutput.mkdir();
            }
            String newFileName = outputFilepathStringBuffer.append("/").append(uuid).append(".png").toString();
            String httpFileName = new StringBuffer("http://")
                    .append(ipAddress)
                    .append(":8019/images/faces/")
                    .append(form.getShopId()).append("/").append(uuid).append(".png").toString();


            file.transferTo(new File(newFileName));

            form.setFaceUrl(httpFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("参数错误");
        }

        Shop shop = shopService.findShopById(form.getShopId());
        try {
            logger.info("api/customer: {}", JsonUtil.toJson(form));
            logger.info(JsonUtil.toJson(form));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        CustomerVO vo = customerService.findByFaceNew(form.getShopId(), form.getFaceUrl());
        try {
            logger.info(JsonUtil.toJson(vo));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return ResultGenerator.genSuccessResult(vo);

    }

    @PostMapping(value = "/api/cardInfo", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取金桥卡余额", notes = "通过顾客id")
    public Result getCustomer(@RequestBody CardInfoForm form) {

        try {
            logger.info("api/cardInfo: {}", JsonUtil.toJson(form));
            logger.info(JsonUtil.toJson(form));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        JinQiaoPayCardItem jinQiaoPayCardItem = JinQiaoPayController.GetCardInfoByMemInterface(form.getCardNo());

        return ResultGenerator.genSuccessResult(jinQiaoPayCardItem.getCurrentMoney());
    }

    @PostMapping(value = "/api/customer/getBalance", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取单个顾客信息", notes = "通过顾客id")
    public Result getBalance(@RequestBody CardInfoForm form) {
        PayCard payCard = customerService.getYpCard(form.getCardNo(),form.getShopId());
        form.setAccountBalance(payCard.getAccountbalance()+payCard.getWxAccountbalance()+payCard.getYktAccountbalance()+payCard.getBzAccountbalance());
        Customer customer = customerService.findByCustomerId(payCard.getCustomerid());
        form.setName(customer.getName());
        return ResultGenerator.genSuccessResult(form);
    }


    @GetMapping(value = "/api/intranet-customers/{shopId}/{pageNum}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取内网顾客信息", notes = "通过顾客id")
    public Result getIntranetCustomerList(@PathVariable Integer shopId,
                                          @PathVariable Integer pageNum) {

        JSONObject result = customerService.getIntranetCustomerList(shopId,pageNum);

        return ResultGenerator.genSuccessResult(result);
    }
    @GetMapping(value = "/api/intranet-customer/{shopId}/{id}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取内网顾客信息", notes = "通过顾客id")
    public Result getIntranetCustomer(@PathVariable Integer shopId,
                                      @PathVariable Integer id) {

        JSONObject result = customerService.getIntranetCustomer(id,shopId);

        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping(value = "/api/customer/delete", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取单个顾客信息", notes = "通过顾客id")
    public Result deleteCustomer(@RequestBody @Valid CustomerForm form) {
        //customerService.updatePaycard();
        //customerService.updatePaycard(form.getShopID());
        //customerService.deletePerson(form.getCustomerID(),form.getShopID());
        //zytkService.PaymentA("2697318823","1",29);
        //customerService.findFace();
        //hzShiMingService.queryBalance("EFB94B2B");
        //hzShiMingFaceService.createPerson(form.getShopID());
        //hzShiMingFaceService.queryFace(form.getShopID());
        //hzShiMingService.faceBind(form.getShopID(),"33012419880907061X","沈鸿杰","H12958017","4");
        //hzShiMingFaceService.deletePerson();
        //hzShiMingService.faceBind(form.getShopID(),"654223199402031514","刘朝政","120992522","04");
        //customerService.addMinZhuFace();
        //customerService.addHefei();
//        customerService.updateYPCard();
        //customerService.rechargeCard();
        //customerService.wujinPayCard();
        customerService.rechargeByMonthDay();
        return ResultGenerator.genSuccessResult("success");
    }

    public static class ShiMingFace implements Callable<String> {
        private String faceUrl;

        public String getFaceUrl() {
            return faceUrl;
        }

        public void setFaceUrl(String faceUrl) {
            this.faceUrl = faceUrl;
        }

        @Override
        public String call() throws Exception {
            logger.info(getFaceUrl());
            return this.faceUrl;
        }
    }

    public static class LocalFace implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "本地人脸对比成功";
        }
    }
}
